package au.com.cmcrc.tradelab.pm.datafeed.yahoo;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import au.com.cmcrc.tradelab.pm.Util;
import au.com.cmcrc.tradelab.pm.datafeed.DataDownload;
import au.com.cmcrc.tradelab.pm.datafeed.StockEntity;
import au.com.cmcrc.tradelab.pm.util.StringUtils;
import au.com.cmcrc.tradelab.pm.util.URLConnectionReader;

import org.apache.log4j.Logger;

public class YahooDataDownload implements DataDownload{
	
	static Logger logger = Logger.getLogger(YahooDataDownload.class);
	
	private ArrayList<String> stocks=new ArrayList<String>();
	private String url="";

	public String getUrl() {
		return url;
	}

	public YahooDataDownload(ArrayList<String> stocks) throws Exception{
		super();
		this.stocks = stocks;
		this.validate();
		logger.info("Entried requested are " +this.stocks.size()+ " less tha 200. Thus OK.");
		this.constructURL();
		logger.info("URL construted: "+this.url);
	}
	
	public ArrayList<StockEntity> download()throws Exception{
		
		ArrayList<StockEntity> stockEntityAL = new ArrayList<StockEntity>();
		
		BufferedReader bufferedReaderObj = URLConnectionReader.getURLReader(this.url);
		
		String inputLine;
		while ((inputLine = bufferedReaderObj.readLine()) != null) 
			stockEntityAL.add(this.getStockEntityObject(inputLine));
		
		return stockEntityAL;
	}

	private StockEntity getStockEntityObject(String urlLine){
		
		StringTokenizer st = new StringTokenizer(urlLine,",");
		if( st.countTokens() > 2){
			logger.error("Data row is not correct "+urlLine);
		}
		
		String stockSymbol = StringUtils.stripLeadingAndTrailingQuotes(st.nextToken());
		double stockValue = new Double(st.nextToken()).doubleValue();
	    		
		return new YahooStockEntity(stockSymbol,stockValue);
		
	}
	
	private void constructURL(){
		this.url = Util.getProperty("url.yahoo.finance.datafeed") + YahooConstants.STOCK_SYMBOL + YahooConstants.ASSIGNMENT;
		
		for(int i=0;i<stocks.size();i++){
			this.url = this.url + "+" + stocks.get(i);
		}
		
		this.url = this.url + YahooConstants.INSTRUCTION_SEPERATOR + 
		                      YahooConstants.FEED_OPTIONS + 
		                      YahooConstants.ASSIGNMENT + 
		                      YahooConstants.FEED_OPTION_SYMBOL + 
		                      YahooConstants.FEED_OPTION_LAST_TRADE;
		
	}
	
	private void validate()throws Exception{
		if(this.stocks.size() > 200){
			logger.error("Yahoo Limits the stocks to 200 and you have requested for " + this.stocks.size());
			throw new Exception("Yahoo Limits the stocks to 200.");			
		}
	}
	

}
